import config from '../../mars/conf/config'
var api = require("../../mars/services/api.js");
let that;
Component({
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 0
        })
      }

      this.jumpToTabbar({
        currentTarget: {
          dataset: {
            page: '0'
          }
        }
      });

      const animationPageOne = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease-out',
      });
      const animationPageTwo = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease-out',
      });
     
      this.animationPageOne = animationPageOne;
      this.animationPageTwo = animationPageTwo;
      // 第一次load,显示活动详情
      this.getUserEventByUserId(wx.getStorageSync('user').id).then((data) => {
        if (!data.length) {
          this.setData({
            showActivityTag: true,
          });
        } else {
          this.setData({
            showActivityTag: false,
            // alreadyPartIn: true
          });
        }
      });

      this.getAllAvailbleEvents().then((data) => {
        let firstActivity = data[0];
        if (!firstActivity) return;
        this.setData({
          activityInfo: firstActivity,
          showActivityBtn: true,
        });
      });
    }
  },
  data: {
    animationPageOne: {},
    animationPageTwo: {},
    // animationPageThree:{},
    showActivityTag: true,
    lastPunchInfo: {
      img_url: "",
      description: "",
      weight: "",
      bmi: "",
      waist: "",
      date: ""
    },
    isIphoneX: false,
    firstPunchInfo: {
      img_url: "",
      description: "",
      weight: "",
      bmi: "",
      waist: "",
      date: ""
    }
  },
  methods: {
    onLoad(options) {
      let groupId = options.groupId;
      let user = wx.getStorageSync("user");
      that = this;
      this.setData({
        isIphoneX: getApp().globalData.isIphoneX
      })
      if (!user) {
        let queryStr = "";
        if (groupId) {
          queryStr = '?groupId=' + groupId;
        }
        // console.log('从圈子页面进入', queryStr)

        wx.getSetting({
          success(res) {
            if (res.authSetting['scope.userInfo']) {
              wx.getUserInfo({
                success(res) {
                  console.log(res.userInfo)
                  let userInfo = res.userInfo;
                  wx.login({
                    success: function (res) {
                      if (res.code) {
                        //发起网络请求
                        console.log(res.code);
                        api.WxRequest(api.checkIsNew, {
                          code: res.code,
                          userInfo: userInfo
                        }, (res) => {
                          wx.setStorageSync('user', res.data);
                          that.joinInGroup(groupId);
                        });
                      }
                    }
                  });
                }
              });
            } else {
              setTimeout(function () {
                wx.navigateTo({
                  url: '/pages/login/login' + queryStr,
                });
              }, 0);
            }
          }
        })

        // setTimeout(function(){
        //   wx.navigateTo({
        //     url: '/pages/login/login' + queryStr,
        //   });
        // }, 0)
      } else if (groupId) {
        this.joinInGroup(groupId);
      }
    },
    onShow() {  
      this.lastPunchInfo();
      this.firstPunchInfo();
    },
    jumpToTabbar(e) {
      let page = e.currentTarget.dataset.page;
      switch (page) {
        case "0":
          wx.switchTab({
            url: '/pages/activityIndex/activityIndex',
          });
          break;
        case "1":
          wx.switchTab({
            url: '/pages/communityIndex/communityIndex',
          });
          break;
        case "2":
          wx.switchTab({
            url: '/pages/calorieIndex/calorieIndex',
          });
          break;
        case "3":
          wx.switchTab({
            url: '/pages/calorDailyAttendance/calorDailyAttendance',
          });
          break;
      }
    },
    animateToPage(e) {
      let f = e.currentTarget.dataset.from;
      let t = e.currentTarget.dataset.to;

      let animationPageOne = this.animationPageOne;
      let animationPageTwo = this.animationPageTwo;
      // let animationPageThree = this.animationPageThree;
      // let animationPageFour = this.animationPageFour;
      if (f == '1') {
        if (!this.data.showActivityTag) {
          return this.jumpToTabbar({
            currentTarget: {
              dataset: {
                page: '3'
              }
            }
          });
        }
        animationPageOne.translateX('-100vh').step();
        this.setData({
          animationPageOne: animationPageOne.export(),
        });
      }
      if (f == '2') {
        // if(t == '1'){
        //   animationPageOne.translateX('0').step();
        //   this.setData({
        //     animationPageOne: animationPageOne.export(),
        //   })
        // }

        if (t == '3') {
          this.jumpToTabbar({
            currentTarget: {
              dataset: {
                page: '3'
              }
            }
          });

          setTimeout(() => {
            animationPageOne.translateX('0').step();
            this.setData({
              showActivityTag: false,
              animationPageOne: animationPageOne.export()
            });
            this.partInActivity();
          })
        }
      }

      if (f == '3') {
        if (t == '4') {
          animationPageThree.translateX('-100vw').step();
          this.setData({
            animationPageThree: animationPageThree.export(),
          })
        }

        if (t == '1') {
          animationPageOne.translateX('0').step();
          this.setData({
            animationPageOne: animationPageOne.export(),
          })
        }
      }

      if (f == '4') {
        if (t == '3') {
          animationPageThree.translateX('0').step();
          // animationPageFour.translateX('100vw').step();
          this.setData({
            animationPageThree: animationPageThree.export(),
            // animationPageFour: animationPageFour.export(),
          })
        }
      }
    },
    startPunch() {
      wx.navigateTo({
        url: '/pages/calorDailyAttendance/calorDailyAttendance',
      })
    },
    joinInGroup(groupId) {
      let userId = wx.getStorageSync('user').id;
      if(!userId) return;
      api.WxRequest(api.partInGroup, {
        groupId: groupId,
        userId: wx.getStorageSync('user').id
      }, (res) => {
        if (res.status) return;
        wx.showToast({
          title: '已接收邀请,加入小组'
        });
      });
    },
    getUserEventByUserId(userId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getUserEventByUserId, {
          userId: userId
        }, (res) => {
          resolve(res.data);
        });
      });
    },
    getEventInfoByEventId(eventId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getEventInfoByEventId, {
          eventId: eventId
        }, (res) => {
          resolve(res.data);
        });
      })
    },
    partInEvent(userId, eventId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.partInEvent, {
          userId: userId,
          eventId: eventId
        }, (res) => {
          resolve(res.data);
        });
      })
    },
    getMenuListByEventId(eventId, day, mealType) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getMenuListByEventId, {
          eventId,
          day,
          mealType
        }, (res) => {
          resolve(res.data);
        });
      })
    },
    getAllAvailbleEvents() {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getAllAvailbleEvents, {}, (res) => {
          resolve(res.data);
        });
      })
    },
    partInActivity() {
      wx.showLoading({
        title: '正在加载中',
      });
      this.partInEvent(wx.getStorageSync('user').id, this.data.activityInfo.id).then(data => {
        wx.hideLoading();
        wx.showToast({
          title: '参加活动成功',
          icon: "none"
        });

        this.setData({
          showActivityTag: false,
          // alreadyPartIn: true
        });
        // this.getMenuListByMealName();
      })
    },
    firstPunchInfo() {
      api.WxRequest(api.getActivityFirstPunch, {
        userId: wx.getStorageSync('user').id
      }, (res) => {
        if (res.data.length) {
          this.setData({
            firstPunchInfo: res.data[0]
          })
        }
      });
    },
    lastPunchInfo() {
      api.WxRequest(api.getActivittFinishPunch, {
        userId: wx.getStorageSync('user').id
      }, (res) => {
        if (res.data.length) {
          this.setData({
            lastPunchInfo: res.data[0]
          })
        }
      });
    }
  }
})